<!-- 选择建设单位 -->
<template>
  <div class="chooseUnit">
    <div class="topSearch">
      <el-input v-model="unitName" size="mini" clearable class="unitName" placeholder="请输入建设单位名称" />
      <div class="search-panel-btn">
        <el-button type="primary" class="pms-button-primary search-btn" @click="doSearch">查询</el-button>
        <el-button size="mini" class="pms-button pms-zr-reset" @click="resetSearch">重置</el-button>
      </div>
    </div>
    <SearchList title="建设单位选择" style="margin-top: 16px;">
      <template v-slot:body>
        <el-tree
          ref="unitRef"
          :class="isEditUnit ? 'editClass' : ''"
          :data="unitData"
          :expand-on-click-node="false"
          :highlight-current="isEditUnit"
          :default-checked-keys="checkedKeys"
          :default-expanded-keys="defaultExpandedKeys"
          :check-strictly="isEditUnit"
          show-checkbox
          node-key="orgId"
          empty-text="加载中，请稍候"
          :props="defaultProps"
          @check="handleClick"
        />
        <!-- show-checkbox !isEditUnit @[eventName]="handleClick" -->
      </template>
    </SearchList>
  </div>
</template>

<script>
// 10000000
import SearchList from '@/components/basic/SearchList'
import { queryOrgApi } from '@/api/attachManagement/electronicSign/eleSignVerConfig'
// import { transTree } from '@/utils'

export default {
    name: 'ChooseUnit',
    components: {
        SearchList
    },
    props: {
        value: {
            type: Array,
            default: () => []
        },
        isEditUnit: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            eventName: this.isEditUnit ? 'node-click' : 'check',
            unitName: '', // 建设单位名称
            checkedKeys: [], // 选中节点的key集合
            checkedNodes: [], // 选中节点的node集合
            defaultExpandedKeys: [10000000], // 默认打开的节点
            defaultProps: {
                children: 'children',
                label: 'orgName'
            },
            unitData: [], // 转化为树形结构的数据
            unitList: [] // 建设单位接口返回的原始数据
        }
    },
    watch: {
        // value: {
        //     immediate: true,
        //     handler(newV) {
        //         if (newV.length) {
        //             // this.defaultExpandedKeys = newV
        //             this.checkedKeys = newV
        //         }
        //         console.log(this.checkedKeys, 'newV')
        //     },
        //     deep: true
        // }
    },
    created() {
        this.queryOrg()
    },
    methods: {
        // 查询建设单位
        queryOrg() {
            queryOrgApi().then(res => {
                if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                this.unitList = res.data
                this.unitData = this.transTree(res.data, res.data[0].parentOrgId)
                if (this.value.length) {
                    const fuUnitList = res.data.filter(item => item.orgId === this.value[0])[0].parentOrgId.toString()
                    this.defaultExpandedKeys = fuUnitList.split().map(item => +item)
                    console.log(this.value, '编辑回显')
                    this.checkedKeys = this.value
                }
            })
        },
        doSearch() {
            if (!this.unitName) {
                return
            }
            this.unitList.forEach(item => {
                const flag = this.fuzzyMatch(item.orgName, this.unitName)
                if (flag) {
                    this.defaultExpandedKeys = []
                    const arrId = []
                    arrId.push(item.orgId)
                    this.defaultExpandedKeys.push(item.parentOrgId)
                    this.$refs.unitRef.setCheckedKeys(arrId)
                }
            })
        },
        fuzzyMatch(strVal, pattern) {
            // 将模式进行转义，防止特殊字符引起正则表达式错误
            const escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

            // 创建正则表达式对象并使用i标志进行不区分大小写的匹配
            const regex = new RegExp(escapedPattern, 'i')

            // 使用test方法进行匹配检查
            return regex.test(strVal)
        },
        // 转树形
        transTree(arr, parentOrgId = 50001440) {
            const tree = []
            arr.forEach(item => {
                if (item.parentOrgId === parentOrgId) {
                    const children = this.transTree(arr, item.orgId)
                    if (children.length) {
                        item.children = children
                    }
                    tree.push(item)
                }
            })
            return tree
        },
        // 勾选点击事件 / 编辑时单选
        handleClick(data, row) {
            if (!this.isEditUnit) {
                this.checkedKeys = row.checkedKeys
                this.checkedNodes = row.checkedNodes
            } else {
                console.log(data, row, '选中1')
                this.checkedKeys = []
                this.checkedNodes = []
                this.$refs.unitRef.setCheckedKeys([])
                this.checkedKeys.push(data.orgId)
                this.checkedNodes.push({
                    orgId: data.orgId,
                    orgName: data.orgName
                })
            }
        },
        // 重置查询
        resetSearch() {
            this.$refs.unitRef.setCheckedKeys([])
            this.checkedKeys = []
            this.checkedNodes = []
            this.unitName = ''
        }
    }
}
</script>

<style lang="scss" scoped>
.chooseUnit {
    // height: auto;
    overflow: auto;
}

.topSearch {
    display: flex;
    justify-content: space-between;

    .unitName {
        width: 50%;
    }
}

::v-deep .el-input--mini .el-input__inner {
    height: 22px;
}

.search-panel-btn {
    display: flex;
    margin-right: 10px;
    .pms-button-primary,
    .pms-button {
        min-width: 60px;
    }
}

::v-deep .el-tree-node__content {
    height: 30px;
    line-height: 30px;
    border-top: 1px solid #e5e5e5;
}

::v-deep .search-list .search-list-wrapper {
    border: none;
}

::v-deep .search-list .search-list-wrapper .search-list-header {
    margin-left: 0;
    padding-left: 0;
}
::v-deep .editClass .el-checkbox__inner {
    border-radius: 10px;
}
</style>
